<template>
    <div class="signin_body">
      <div class="signin_container">
        <div class="head">
          <img class="logo" src="../assets/logo.png" />
          <div class="name">
            <div class="title">高中信息技术</div>
            <div class="tips">题库系统</div>
          </div>
        </div> 
        <el-form label-position="top" :rules="state.rules" :model="state.ruleForm" ref="signinForm" class="signinForm">
          
            <el-form-item label="实名（中文汉字）" prop="real_name">
              <div class="send_phone_code"> 
                <el-input type="text" v-model="state.ruleForm.real_name" autocomplete="off" clearable @blur="checkUsernameUsableBlur"></el-input>
                <div v-show="state.realnameOK"><el-icon size="large"><SuccessFilled /></el-icon></div>
                <div v-show="state.realnameOK == false"><el-icon size="large"><CircleCloseFilled /></el-icon></div>
              </div>
              <el-text></el-text>
            </el-form-item>
        
         <el-form-item label="手机（11位数字）" prop="phone">
          <div class="send_phone_code"> 
            <el-input type="text" v-model="state.ruleForm.phone" autocomplete="off" clearable @blur="checkPhoneUsableBlur"></el-input>
             <div v-show="state.phoneNumberOk"><el-icon size="large"><SuccessFilled /></el-icon></div>
             <div v-show="state.phoneNumberOk == false"><el-icon size="large"><CircleCloseFilled /></el-icon></div>
          </div>
          </el-form-item>
          <el-form-item label="验证码（不区分大小写）" prop="captcha_code">
            <div class="send_phone_code">  
                <el-input type="text" v-model.trim="state.captchaCode" autocomplete="off" clearable @blur="checkCapchaCodeBlur"></el-input>
                <div v-show="state.captchaCodeOk"><el-icon size="large"><SuccessFilled /></el-icon></div>
                <div v-show="state.captchaCodeOk == false"><el-icon size="large"><CircleCloseFilled /></el-icon></div>
                <img :src="state.captcha_picture" class="captcha_picture" @click="updatacaptcha" />
            </div>
          </el-form-item>
          <el-form-item label="短信验证码" prop="phone_code" >
            <div class="send_phone_code" ref="sendPhoneCoseRef">     
                <el-input type="text" v-model="state.ruleForm.phoneCode" autocomplete="off" :disabled="state.phoneCodeInput" clearable @blur="checkPhoneCodeBlur"></el-input>
                <el-text v-show="state.phoneCodeOK">  <el-icon size="large"><SuccessFilled /></el-icon></el-text>
                <el-button v-show="state.showGetPhoneCodeButton" type="primary" round size="small" @click="getPhoneCodeClick()" :disabled="state.getPhoneCodeButtonOK">获取短信</el-button>
                
            </div> 
            <span v-show="!state.showGetPhoneCodeButton">{{ state.count }}s后获取</span>
        </el-form-item>
     
          <div class="twoButton"> 
            <el-button type="primary" @click="submitForm" :disabled="state.submitButtonVisible">申请</el-button>
            <el-button type="warning" @click="loginClick">去登录</el-button>
          </div>
        </el-form>
      </div>
    </div>
  </template>
  
<script setup>
  import axios from '@/utils/axios'
  import { reactive, ref } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { localSet, pathMap, logoUrl } from '@/utils'
  import { onMounted } from "@vue/runtime-core"
  // import router from '../router'
  import { SuccessFilled, CircleCloseFilled } from '@element-plus/icons-vue'
  import { ElMessage } from 'element-plus'

  const route = useRoute()
  const router = useRouter()
  const signinForm = ref(null) 
  const sendPhoneCoseRef = ref(null)
  // 验证手机号码是否合法
  const checkTelephone =(rule, telephone, callback)=> {
    var reg=/^[1][3,4,5,7,8][0-9]{9}$/g;
    if (!reg.test(telephone)) {
        return false;
    } else {
        return true;
    }
  }
  const state = reactive({
    showGetPhoneCodeButton: true,
    count: '',
    timer: null,
    realnameOK: false,
    phoneCodeOK: false,
    phoneCodeInput: true,
    phoneNumberOk: false,
    captchaCodeOk: false,
    submitButtonVisible: true,
    getPhoneCodeButtonOK: true,
    clientCode: Number,
    sendPhoneCodeVisible: false,
    captcha_picture: '',
    captchaCode: '',    
    ruleForm: {
      real_name: '',
      phone: '',
      phoneCode: '',
    },
    checked: true,
    rules: {
      real_name: [
        { required: 'true', message: '实名不能空', trigger: 'blur' }
      ],
      phone: [
        { required: 'true', message: '手机不能空', trigger: 'blur' },
        {validator: checkTelephone, trigger: 'blur'}
      ],
      phoneCode:[
        { required: 'true', message: '验证码不能空', trigger: 'blur' }
      ],
    }
  })
  // 通过服务器检测手机验证码是否正确
  const sendCheckPhoneCode=()=>{
    let params = {
      phoneNumber: state.ruleForm.phone, 
      phoneCode: state.ruleForm.phoneCode,
      clientCode: state.clientCode,
      captchaCode: state.captchaCode,
    }
    axios.get('/CheckPhoneCode/', {params}).then(res => {
        if(res.code==200){
          state.phoneCodeOK = res.data.results
        }else{
          state.phoneCodeOK = false
          ElMessage.error("手机号码不可用！")
        }
        state.submitButtonVisible = !state.phoneCodeOK
    })
    .catch((error)=>{
      console.log("手机验证码失败", error)
    })
  }
  // 触发发送短信按钮开启
  const verifySendPhoneCodeButtonUsable=()=>{
    console.log("三个变量：", state.realnameOK,state.phoneNumberOk,state.captchaCodeOk)
    if(state.realnameOK & state.phoneNumberOk & state.captchaCodeOk)
    {
      state.getPhoneCodeButtonOK = false    //发送短信按钮可用（开启）
    }
  }
  // 监测用户名是否可用
  const checkUsernameUsableBlur=()=>{
    let params = { real_name: state.ruleForm.real_name}
    if(state.ruleForm.real_name.trim() == ''){
      ElMessage.error("用户名不能为空")
      return false
    }
    axios.get('/CheckRealNameUsableAPIView/', {params}).then(res => {
      console.log("实名查询返回：", res)
        if(res.code==200){
          state.realnameOK = res.data.results
          verifySendPhoneCodeButtonUsable()
        }else{
          state.realnameOK = false
          state.getPhoneCodeButtonOK = true      //关闭发送短信按钮可用
          ElMessage.error("该姓名不可用！")
        }        
    })
    .catch((error)=>{
      state.realnameOK = false
      console.log("检测姓名失败：", error)
    })
  }

  // 手机验证码验证事件
  const checkPhoneCodeBlur=()=>{
    if(sendCheckPhoneCode() ==false){
      ElMessage.error("验证码输入错误，请点击图片后再输入！")
    }
  }
  // 通过服务器检验手册号码是否可用，如果可用，检测开启发送短信按钮
  const sendCheckPhoneUsable=()=>{
    let params = { phoneNumber: state.ruleForm.phone}
    axios.get('/CheckPhoneUsable/', {params}).then(res => {
      console.log("手机号码返回：", res)
        if(res.code==200){
          state.phoneNumberOk = res.data.results
          verifySendPhoneCodeButtonUsable()
        }else{
          state.phoneNumberOk = false
          state.getPhoneCodeButtonOK = true     //发送短信按钮不可用
          ElMessage.error("手机号码已被注册或无效！")
        }       
        state.getPhoneCodeButtonOK = true
    })
    .catch((error)=>{
      state.phoneNumberOk = false
      console.log("检测验证码失败", error)
    })
  }
  // 处理手机号码可用事件
  const checkPhoneUsableBlur=()=>{
    sendCheckPhoneUsable()
  }
  // 通过服务器检验校对用户输入的验证码是否正确
  const sendCheckCapchaCode=()=>{
    let params = { clientCode: state.clientCode, captchaCode: state.captchaCode }
    axios.get('/CheckCaptchaCode/', {params}).then(res => {
        if(res.code==200){
          state.captchaCodeOk = true          
          verifySendPhoneCodeButtonUsable()
        }else{
          state.captchaCodeOk = false
          state.sendPhoneCodeVisible = false
          state.getPhoneCodeButtonOK = true      //关闭发送短信按钮可用
          ElMessage.error("验证码错误，请刷新图片重新输入！")
        }
    })
    .catch((error)=>{
      console.log("检测验证码失败", error)
    })
  }
  // 处理输入图像验证码事件
  const checkCapchaCodeBlur=()=>{
    sendCheckCapchaCode()
  }
  //获取图像
  const getCaptchaPictureWithClientCode=()=>{
    const min = 100000
    const max = 999990
    const a = Math.floor(Math.random() * (max - min + 1)) + min
    state.clientCode = a
    console.log("图像验证码：", state.clientCode)
    let params = { clientCode: state.clientCode }
    axios.get('/CaptchaPictureWithClientCode/', {params}).then(res => {
        if(res.code==200){
          console.log('获取base64图片成功：', res)
            state.captcha_picture='data:image/png;base64,' + res.data.results
        }else{
            ElMessage.error("获取图像失败，请联系管理员！")
        }          
    })
    .catch((error)=>{
      console.log("获取图像失败", error)
      ElMessage.warning("获取图片异常，请联系管理员！")
    })
  }
  onMounted(()=>{
    console.log("我已经来到注册页面了")
    getCaptchaPictureWithClientCode()  
  })
  //倒计时60秒
  const countDown=()=>{
    const TIME_COUNT = 60;
    if(!state.timer){
      state.count =TIME_COUNT;
      state.showGetPhoneCodeButton = false;
      state.timer = setInterval(()=>{
        if(state.count>0 && state.count<=TIME_COUNT){
          state.count--;
        }else{
          state.showGetPhoneCodeButton = true;
          clearInterval(state.timer);
          state.timer = null;
        }
      },1000)
    }
  }
  //发送手机短信息验证码
  const getPhoneCodeClick=()=>{
    let params = {
      phoneNumber: state.ruleForm.phone,      
      clientCode: state.clientCode,
      captchaCode: state.captchaCode,
    }
    axios.get('/SendCodeView/', {params}).then(res => {
        if(res.code==200){
          state.phoneCodeInput = false      //开启短信息验证码可用
          countDown()
          ElMessage.success("发送成功，请查看手机短信息，有效时间为3分钟！")
        }else{
          state.ruleForm.phone = ""
          state.captchaCode = ""
          state.phoneNumberOk = false
          state.captchaCodeOk = false
          ElMessage("发送失败，重新填写资料")
          console.log("发送手机验证码错误：", res)
        }        
    })
    .catch((error)=>{
      console.log("发送手机验证码失败", error)
    })
  }
  const submitForm = async () => {
    signinForm.value.validate((valid, object) => {
      if (valid) {
        const { inviter } = route.query
        let params = {
          phoneNumber: state.ruleForm.phone,
          clientCode: state.clientCode,
          captchaCode: state.captchaCode,
          real_name: state.ruleForm.real_name,
          phoneCode: state.ruleForm.phoneCode,
          inviter : inviter,
        }
        axios.post('/RegisterView/', params).then(res => {
          console.log("服务器返回注册信息：", res)
          if (res.code==200 || res.code==201){
            ElMessage.success("注册成功, 密码是123456，请联系管理员激活账号")
            // router.push("/login") 
            // window.location.href = '/login'
          }else if(res.code==1017){
            // console.log("注册错误消息：",res)
            ElMessage.error("验证码过期了")
          }else{
            console.log("注册失败：",res)
            ElMessage.error("注册失败")
          }
        }).catch((error)=>{
          console.log(error)
          // state.ruleForm.captcha_code = ''
        })
      } else{  //输出表单没有通过的原因
        console.log("表单没有通过！",obj)
        for (let key in obj) {
          console.log(obj[key][0].message)
          return false;
        }
      }
    })
  }
  //更新图像验证码
  const updatacaptcha=(val)=>{
    state.captchaCode = ''
    getCaptchaPictureWithClientCode()
  }
  //跳转到登录页面
  const loginClick=()=>{
    router.push('/login')
  }
  </script>
  
  <style scoped>
    .signin_body {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      background-color: #fff;
    }
    .signin_container {
      width: 400px;
      height: 500px;
      background-color: #fff;
      border-radius: 4px;
      box-shadow: 0px 21px 41px 0px rgba(0, 0, 0, 0.2);
    }
    .head {
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 20px 0 10px 0;
    }
    .head img {
      width: 80px;
      height: 80px;
      margin-right: 10px;
    }
    .head .title {
      font-size: 28px;
      color: #1BAEAE;
      font-weight: bold;
    }
    .head .tips {
      font-size: 12px;
      color: #999;
    }
    .signinForm {
      width: 80%;
      margin: 0 auto;
    }

    .captcha_picture{
      width:80px;
      height: 30px;
      cursor:pointer;
    }
    .twoButton{
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .send_phone_code{
        display: flex;
        flex-flow: row nowrap;
        
    }
  </style>